package userserv

import (
	"encoding/json"
	"log"
	"message"
	"net/http"
)

func replyLoadMsg(msg []string, w http.ResponseWriter) {
	if msg == nil {
		w.Write(nil)
	} else {
		s, err := json.Marshal(msg)
		if err == nil {
			w.Write(s)
		} else {
			w.Write(nil)
		}
	}
}

func onLoadMsg(w http.ResponseWriter, r *http.Request) {
	var account string
	account = r.Header.Get("account")

	log.Printf("loadMsgs, account:%s\n", account)

	var start = -10
	var stop = -1

	// load last 10 message
	msg, err := message.LoadUnReadMessage(account, start, stop)
	if err != nil {
		log.Printf("loadMsg err:", err)
	}

	replyLoadMsg(msg, w)
}

func init() {
	myMux.muxHandlers.HandleFunc("/loadMsg", onLoadMsg)
}
